package ext.mango.ab.so;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ext.mango.aa.eo.EOBaseCode;
import ext.mango.ab.eo.EOABHouseKeeper;
import ext.mango.ab.eo.EOABHouseKeeperDetail;
import ext.mango.ab.eo.EOABHouseKeeperTypeItems;
import ext.mango.ab.po.HouseKeeper;
import ext.mango.functions.Func;
import mango.functions.FuncDate;
import mango.functions.FuncString;
import mango.orm.DaoFactory;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;
import mango.service.Service;
import mango.web.Info;

@Service
public class SOABHouseKeeper {

    private String saveAndSearchCode(String codeType, String codeall) {
        String codeName = "";
        String code = "";
        int idx = codeall.indexOf("-");
        if (idx > 0) {
            code = codeall.substring(0, idx).trim();
            codeName = codeall.substring(idx + 1);
            String sql = "select '1' from basecode where codetype=? and code=?";
            String ret = DaoFactory.c(sql).setParameter(codeType, code).getStringValue();
            if (!"1".equals(ret)) {
                new EOBaseCode().setCodeType(codeType).setCode(code).setCodeName(codeName).save();
            }
            return code;
        }
        return codeall;
    }

    public boolean saveHouseKeeper(EOABHouseKeeper eo, HouseKeeper action) {
        if (FuncString.isBlank(eo.getID())) {
            eo.setMakeDate(new Date()).setMakeTime(FuncDate.getCurrentTime())
                    .setModifyDate(new Date()).setModifyTime(FuncDate.getCurrentTime());
            eo.setID(Func.getSequenceNo("KEEP"));
            eo.setSpendType(this.saveAndSearchCode("spendtype", eo.getSpendType()));
            if (FuncString.isBlank(eo.getMoney()) || FuncString.isBlank(eo.getItems())
                    || FuncString.isBlank(eo.getSpendType())) {
                return false;
            }
            if (!this.saveHouseKeeperDetail(eo, action)) {
                return false;
            }
            eo.save();
        }
        else {
            EOABHouseKeeper k = (EOABHouseKeeper) eo.unique();
            eo.setSpendType(this.saveAndSearchCode("spendtype", eo.getSpendType()));
            eo.setMakeDate(k.getMakeDate()).setMakeTime(k.getMakeTime()).setModifyDate(new Date())
                    .setModifyTime(FuncDate.getCurrentTime());
            if (!this.saveHouseKeeperDetail(eo, action)) {
                return false;
            }
            eo.update();
        }
        return true;
    }

    private boolean saveHouseKeeperDetail(EOABHouseKeeper eo, HouseKeeper action) {
        String oitems = eo.getItems();
        String omoney = eo.getMoney();
        oitems = oitems.replaceAll(",|，|。|;|；|、|：|:|/|\\|", " ");
        oitems = oitems.replaceAll("\\p{Blank}+", " ");
        omoney = omoney.replaceAll(",|，|。|;|；|、|：|:|/|\\|", " ");
        omoney = omoney.replaceAll("\\p{Blank}+", " ");

        String[] sItems = oitems.split(" ");
        String[] sMoney = omoney.split(" ");
        if (sItems.length != sMoney.length) {
            action.addInfo(Info.ERROR, "项目和金额数量必须相等！");
            return false;
        }
        double[] moneys = new double[sMoney.length];
        for (int i = 0; i < sMoney.length; i++) {
            try {
                moneys[i] = Double.parseDouble(sMoney[i]);
            }
            catch (Exception e) {
                action.addInfo(Info.ERROR, "金额必须全部为数字！");
                return false;
            }
        }
        
        // 保存详细
        String delsql = "delete from ABHouseKeeperDetail where pid=?";
        DaoFactory.c(delsql).setParameter(eo.getID()).executeUpdate();
        DBSession session = DBSessionFactory.getCurrentSession();
        List<EOABHouseKeeperDetail> details = new ArrayList<EOABHouseKeeperDetail>();
        for (int i = 0; i < sMoney.length; i++) {
            EOABHouseKeeperDetail detail = new EOABHouseKeeperDetail();
            detail.setID(Func.getSequenceNo("ITEM"))
                  .setActionDate(eo.getActionDate())
                  .setPID(eo.getID())
                  .setMakeDate(new Date())
                  .setMakeTime(FuncDate.getCurrentTime())
                  .setMoney(moneys[i])
                  .setOperator(action.getCurrentUser().getId())
                  .setSpendType(eo.getSpendType())
                  .setSpendName(Func.getCodeName("spendtype", eo.getSpendType()))
                  .setSubSpendName(sItems[i])
                  .setActionMonth(FuncDate.parse("yyyy-MM", eo.getActionDate()));
            details.add(detail);
            
            EOABHouseKeeperTypeItems item = new EOABHouseKeeperTypeItems();
            item.setSpendType(eo.getSpendType());
            item.setItem(sItems[i]);
            session.saveIfNotExists(item);
        }
        session.save(details);
        session.commit();
        return true;
    }
}
